/**
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import {
  Row,
  Col,
  Card,
  Button,
  Divider,
  Icon,
  Tabs,
  Form,
  Input,
  Radio,
  message,
  Upload
} from "antd";
import Avatar from "../components/avatar";
import { connect } from "react-redux";
import ResetPw from "../components/ResetPw";
import axios from "../../apis/api";
import qs from "qs";
import { actions } from "../../reducers/main";
import { host } from "../../config/config";
import ImgCrop from "../components/ImgCrop";

const { TabPane } = Tabs;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};

const mapStateToProps = (state, ownProps) => {
  return {
    user: state.main.user
  };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchInitData: next => dispatch(actions.fetchInitData(next))
  };
};

const infoLift = [
  {
    icon: "user",
    label: "登录名称",
    key: "loginName"
  },
  {
    icon: "phone",
    label: "手机号码",
    key: "phonenumber"
  },
  {
    icon: "team",
    label: "所属部门",
    key: "deptName",
    render: user => {
      return <span>{user && user.dept && user.dept.deptName}</span>;
    }
  },
  {
    icon: "mail",
    label: "邮箱地址",
    key: "email"
  },
  {
    icon: "calendar",
    label: "创建时间",
    key: "createTime"
  }
];

class Person extends Component {
  state = {
    loading: false
  };

  saveUserInfo = e => {
    e.preventDefault();
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        const { user } = this.props;
        const { userName, phonenumber, email, sex } = values;
        try {
          this.setState({
            loading: true
          });
          const checkPhone = await axios.post(
            "/system/user/checkPhoneUnique",
            qs.stringify({
              phonenumber,
              userId: user.userId
            })
          );
          if (checkPhone !== 0) {
            message.error("该手机号码已经被占用");
            this.setState({
              loading: false
            });
            return;
          }
          const checkMail = await axios.post(
            "/system/user/checkEmailUnique",
            qs.stringify({
              email,
              userId: user.userId
            })
          );
          if (checkMail !== 0) {
            message.error("该邮箱已经被占用");
            this.setState({
              loading: false
            });
            return;
          }
          const saveInfo = await axios.post(
            "/system/user/profile/update",
            qs.stringify({
              userName,
              phonenumber,
              email,
              sex,
              id: ""
            })
          );
          console.log(saveInfo);
          if (saveInfo.code === 0) {
            message.success("操作成功");
            this.props.fetchInitData(() => {});
          } else {
            message.error(saveInfo.msg);
          }
          this.setState({ loading: false });
        } catch (e) {
          this.setState({
            loading: false
          });
          console.log(e);
        }
      }
    });
  };

  uploadChange = info => {
    if (info.file.status === "done") {
      message.success(`上传成功`);
      this.props.fetchInitData(() => {});
    } else if (info.file.status === "error") {
      message.error(`头像上传失败`);
    }
  };

  componentDidMount() {}

  render() {
    const { user } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { loading } = this.state;
    const props = {
      modalTitle: "修改头像",
      width: 500, //裁剪宽度
      height: 500, //裁剪高度
      resize: true, //裁剪是否可以调整大小
      resizeAndDrag: true, //裁剪是否可以调整大小、可拖动
      modalWidth: 600 //弹窗宽度
    };
    return (
      <div>
        <Row gutter={10}>
          <Col span={6}>
            <Card title="个人资料">
              <div style={{ textAlign: "center" }}>
                <Avatar size={90} icon="user" />
              </div>
              <div style={{ textAlign: "center" }}>
                <ImgCrop {...props}>
                  <Upload
                    showUploadList={false}
                    name="avatarfile"
                    action={`${host}/system/user/profile/updateAvatar`}
                    onChange={this.uploadChange}
                    accept="image/*"
                  >
                    <Button type="link">修改头像</Button>
                  </Upload>
                </ImgCrop>
              </div>
              <Divider style={{ margin: "10px 0" }} />
              {infoLift.map(item => (
                <div key={item.key}>
                  <Row gutter={10}>
                    <Col span={8}>
                      <Icon type={item.icon} />
                      &nbsp;&nbsp;{item.label}：
                    </Col>
                    <Col span={16} style={{ textAlign: "right" }}>
                      {item.render ? item.render(user) : user[item.key]}
                    </Col>
                  </Row>
                  <Divider style={{ margin: "10px 0" }} />
                </div>
              ))}
            </Card>
          </Col>
          <Col span={18}>
            <Card title="基本资料">
              <Tabs defaultActiveKey="1">
                <TabPane tab="基本资料" key="1">
                  <div style={{ width: 600 }}>
                    <Form {...formItemLayout} autoComplete="off">
                      <Form.Item label={"用户名称"}>
                        {getFieldDecorator("userName", {
                          initialValue: user.userName || "",
                          rules: [{ required: true, message: "请输入用户名称" }]
                        })(
                          <Input
                            placeholder="请输入用户名称"
                            autoComplete="off"
                          />
                        )}
                      </Form.Item>
                      <Form.Item label={"手机号码"}>
                        {getFieldDecorator("phonenumber", {
                          initialValue: user.phonenumber || "",
                          rules: [
                            {
                              required: true,
                              message: "请输入手机号码"
                            },
                            {
                              validator: (rule, value, callback) => {
                                if (/^[0-9]{11}$/.test(value)) {
                                  callback();
                                } else {
                                  callback(
                                    new Error("请输入正确的11位手机号码")
                                  );
                                }
                              }
                            }
                          ]
                        })(
                          <Input
                            placeholder="请输入手机号码"
                            autoComplete="off"
                          />
                        )}
                      </Form.Item>
                      <Form.Item label={"邮箱"}>
                        {getFieldDecorator("email", {
                          initialValue: user.email || "",
                          rules: [
                            {
                              required: true,
                              message: "请输入邮箱"
                            },
                            {
                              type: "email",
                              message: "请输入正确的邮箱地址"
                            }
                          ]
                        })(
                          <Input placeholder="请确认邮箱" autoComplete="off" />
                        )}
                      </Form.Item>
                      <Form.Item label={"性别"}>
                        {getFieldDecorator("sex", {
                          initialValue: user.sex || "0",
                          rules: [{ required: true, message: "请选择性别" }]
                        })(
                          <Radio.Group>
                            <Radio value="0">男</Radio>
                            <Radio value="1">女</Radio>
                          </Radio.Group>
                        )}
                      </Form.Item>
                    </Form>
                    <div style={{ textAlign: "center" }}>
                      <Button
                        onClick={this.saveUserInfo}
                        type="primary"
                        htmlType="submit"
                        loading={loading}
                      >
                        保存
                      </Button>
                    </div>
                  </div>
                </TabPane>
                <TabPane tab="修改密码" key="2">
                  <div style={{ width: 600 }}>
                    <ResetPw handleClose={() => {}} hide={true} />
                  </div>
                </TabPane>
              </Tabs>
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}

export default Form.create()(
  connect(mapStateToProps, mapDispatchToProps)(Person)
);
